package com.sbs.gaoxinqutoilet.myapp;

import android.content.Context;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sbs.gaoxinqutoilet.BuildConfig;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.entity.UserInforEntity;
import com.sbs.gaoxinqutoilet.store.PersistentCookieStore;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.Utils;
import com.tencent.tinker.loader.app.TinkerApplication;
import com.tencent.tinker.loader.shareutil.ShareConstants;
import com.zhy.autolayout.config.AutoLayoutConifg;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by 聪明一只哈 on 2018/5/30.
 * Time: 2018/5/30  10:10//com.sbs.gaoxinqutoilet.MyApp.MyApplication
 */

public class MyApplication extends TinkerApplication {

    private static String address;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    public static Context sContext;
    private static MyApplication sApplication;

    public MyApplication() {
        //这里设置你在平台上的配置
        super(ShareConstants.TINKER_ENABLE_ALL, "com.sbs.gaoxinqutoilet.myapp.MyApplicationLike",
                "com.tencent.tinker.loader.TinkerLoader", false);
    }


    @Override
    public void onCreate() {
        super.onCreate();

        String simpleName = MyApplicationLike.class.getName();
        LogUtils.i("showshow", "onCreate: "+simpleName);

        sApplication = this;
        sContext = getApplicationContext();
        //使用autolayot
        AutoLayoutConifg.getInstance().useDeviceSize().init(this);
        //初始化okhttp
        initOKHttps();

        //初试化高德地图
        initGaode();

    }



    public static UserInforEntity userInforEntity;

    public static UserInforEntity getUserInforEntity() {
        return userInforEntity;
    }

    public static void setUserInforEntity(UserInforEntity userInforEntity) {
        MyApplication.userInforEntity = userInforEntity;
    }

    //-----------------保存个人信息-----------------------------------------
    public static UserEntity userEntity;

    public static UserEntity getUserEntity() {
        return userEntity;
    }

    public static void setUserEntity(UserEntity userEntity) {
        MyApplication.userEntity = userEntity;
    }
    //-----------------保存个人信息-----------------------------------------

    public static MyApplication getApplicationIntstance() {
        return sApplication;
    }

    public static Context getContext() {
        return sApplication;
    }


    /**
     * okhttputils 初始化
     */
    private void initOKHttps() {

        CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(getApplicationContext()),
                CookiePolicy.ACCEPT_ALL);


        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

        if(BuildConfig.LEO_DEBUG) {
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        }else{
            logging.setLevel(HttpLoggingInterceptor.Level.NONE);
        }



        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new MyApplication.CacheInterceptor())
                .writeTimeout(30000L, TimeUnit.SECONDS)
                .readTimeout(30000L, TimeUnit.SECONDS)
                .connectTimeout(30000L, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .cookieJar(new JavaNetCookieJar(cookieHandler))
                .build();

        OkHttpUtils.initClient(okHttpClient);

    }

    public class CacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            int code = response.code();
            Log.e("显示","code值"+code);
            Response response1 = response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    //cache for 30 days
                    .header("Cache-Control", "max-age=" + 3600 * 24 * 30)

                    .build();
            return response1;
        }
    }

    private void initGaode() {

        try{
            //初始化client
            locationClient = new AMapLocationClient(this.getApplicationContext());
            locationOption = getDefaultOption();
            //设置定位参数
            locationClient.setLocationOption(locationOption);
            // 设置定位监听
            locationClient.setLocationListener(locationListener);

            locationClient.startLocation();
        }catch (Exception e){

        }



    }

    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(true);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(1000*4*1);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(true);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        mOption.setSensorEnable(true);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(false); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            address = Utils.getLocationStr(location);
            //LogUtils.i("hashiqiLoacation", "onLocationChanged: "+address);
            if(address.contains("市")){
                address=address.substring(address.indexOf("市")+1,address.length());
                LogUtils.i("hashiqiLoacation", "onLocationChanged: "+address);
            }

        }
    };

    public static String getAddress() {
        return address;
    }




}
